package com.lzf.quickcheck.screens.home

import android.Manifest
import android.content.ContentValues
import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.widget.Toast
import androidx.camera.core.*
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CameraAlt
import androidx.compose.material.icons.filled.Videocam
import androidx.compose.material.icons.rounded.ShoppingCart
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleOwner
import androidx.navigation.NavController
import com.lzf.quickcheck.screens.home.Yolo
import kotlinx.coroutines.*
import java.io.OutputStream
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

@Composable
fun CameraScreen(navController: NavController) {
    val context = LocalContext.current
    val lifecycleOwner = LocalContext.current as LifecycleOwner
    val cameraProviderFuture = remember { ProcessCameraProvider.getInstance(context) }
    val executor = remember { Executors.newSingleThreadExecutor() }
    var imageCapture by remember { mutableStateOf<ImageCapture?>(null) }
    var isAutoCapture by remember { mutableStateOf(false) }
    val coroutineScope = rememberCoroutineScope()

    // 使用 DisposableEffect 释放资源
    DisposableEffect(lifecycleOwner) {
        onDispose {
            // 销毁相机资源
            cameraProviderFuture.get().unbindAll()
        }
    }

    LaunchedEffect(isAutoCapture) {
        while (isAutoCapture) {
            takePhoto(imageCapture, context, executor)
            delay(1000)  // 每秒拍摄一张
        }
    }

    Box(modifier = Modifier.fillMaxSize()) {
        AndroidView(
            modifier = Modifier.fillMaxSize(),
            factory = { ctx ->
                val previewView = androidx.camera.view.PreviewView(ctx)
                val cameraProvider = cameraProviderFuture.get()
                val preview = Preview.Builder().build().also {
                    it.setSurfaceProvider(previewView.surfaceProvider)
                }

                imageCapture = ImageCapture.Builder()
                    .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
                    .build()

                val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
                cameraProvider.unbindAll()
                cameraProvider.bindToLifecycle(
                    lifecycleOwner, cameraSelector, preview, imageCapture
                )

                previewView
            }
        )

        // 拍照按钮
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp),
            verticalArrangement = Arrangement.Bottom,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Row {
                FloatingActionButton(
                    onClick = {
                        isAutoCapture = !isAutoCapture
                        if (isAutoCapture) {
                            Toast.makeText(context, "Auto capture started", Toast.LENGTH_SHORT)
                                .show()
                        } else {
                            Toast.makeText(context, "Auto capture stopped", Toast.LENGTH_SHORT)
                                .show()
                        }
                    },
                    modifier = Modifier.padding(end = 16.dp)
                ) {
                    Icon(
                        imageVector = androidx.compose.material.icons.Icons.Default.Videocam,
                        contentDescription = "Auto Capture"
                    )
                }

                FloatingActionButton(
                    onClick = {
                        Toast.makeText(context, "Taking photo...", Toast.LENGTH_SHORT).show()
                        takePhoto(imageCapture, context, executor)
                    }
                ) {
                    Icon(
                        imageVector = Icons.Filled.CameraAlt,
//                        imageVector = androidx.compose.material.icons.Icons.Default.Camera,
                        contentDescription = "Capture"
                    )
                }
            }
        }
    }
}

// 拍照并处理图像
private fun takePhoto(
    imageCapture: ImageCapture?,
    context: Context,
    executor: ExecutorService
) {
    val outputOptions = ImageCapture.OutputFileOptions.Builder(
        context.contentResolver,
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
        ContentValues().apply {
            put(MediaStore.MediaColumns.DISPLAY_NAME, "IMG_${System.currentTimeMillis()}.jpg")
            put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
            put(
                MediaStore.MediaColumns.RELATIVE_PATH,
                "${Environment.DIRECTORY_PICTURES}/QuickCheck"
            )
        }
    ).build()

    imageCapture?.takePicture(outputOptions, executor, object : ImageCapture.OnImageSavedCallback {
        override fun onImageSaved(output: ImageCapture.OutputFileResults) {
            output.savedUri?.let { uri ->
                processAndUploadImage(uri, context)
            }
        }

        override fun onError(exception: ImageCaptureException) {
            Log.e("CameraScreen", "Photo capture failed: ${exception.message}")
        }
    })
}

// 处理并上传图像
private fun processAndUploadImage(uri: Uri, context: Context) {
    val bitmap = uriToBitmap(uri, context) ?: return
    val processedBitmap = Yolo().processImage(bitmap)

    saveImageToGallery(processedBitmap, context)
    uploadToServer(uri, context)
}

// 读取 Bitmap
private fun uriToBitmap(uri: Uri, context: Context): Bitmap? {
    return try {
        context.contentResolver.openInputStream(uri)?.use { inputStream ->
            android.graphics.BitmapFactory.decodeStream(inputStream)
        }
    } catch (e: Exception) {
        Log.e("CameraScreen", "Failed to convert URI to Bitmap: ${e.message}")
        null
    }
}

// 保存到本地相册
private fun saveImageToGallery(bitmap: Bitmap, context: Context) {
    val contentValues = ContentValues().apply {
        put(MediaStore.Images.Media.DISPLAY_NAME, "Processed_${System.currentTimeMillis()}.jpg")
        put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
        put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES)
    }

    val uri =
        context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
    uri?.let {
        context.contentResolver.openOutputStream(it)?.use { outputStream ->
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
        }
    }
}

// 上传到服务器
private fun uploadToServer(uri: Uri, context: Context) {
    // 模拟网络请求
    CoroutineScope(Dispatchers.IO).launch {
        try {
            delay(2000) // 模拟网络延迟
            Log.d("CameraScreen", "Upload success: $uri")
        } catch (e: Exception) {
            Log.e("CameraScreen", "Upload failed: ${e.message}")
        }
    }
}
